package com.fy.utils;

import java.util.Set;
import java.util.TreeSet;

public class SnowflakeIdGenerator {

  // 初始时间戳(纪年)，可用雪花算法服务上线时间戳的值
  private static final long INIT_EPOCH = 1649059688068L;

  // 记录最后使用的毫秒时间戳，主要用于判断是否同一毫秒，以及用于服务器时钟回拨判断
  private long lastTimeMillis = -1L;

  // dataCenterId占用的位数
  private static final long DATA_CENTER_ID_BITS = 5L;
  private static final long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_ID_BITS);
  private long datacenterId;

  // workId占用的位数
  private static final long WORKER_ID_BITS = 5L;
  private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
  private long workerId;

  // 最后12位，代表每毫秒内可产生最大序列号，即 2^12 - 1 = 4095
  private static final long SEQUENCE_BITS = 12L;
  private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);
  private long sequence;

  // workId位需要左移的位数 12
  private static final long WORK_ID_SHIFT = SEQUENCE_BITS;
  // dataCenterId位需要左移的位数 12+5
  private static final long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
  // 时间戳需要左移的位数 12+5+5
  private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS;

  public SnowflakeIdGenerator(long datacenterId, long workerId) {
    if (datacenterId < 0 || datacenterId > MAX_DATA_CENTER_ID) {
      throw new IllegalArgumentException(
          String.format("datacenterId值必须大于0并且小于%d", MAX_DATA_CENTER_ID));
    }
    if (workerId < 0 || workerId > MAX_WORKER_ID) {
      throw new IllegalArgumentException(String.format("workId值必须大于0并且小于%d", MAX_WORKER_ID));
    }
    this.workerId = workerId;
    this.datacenterId = datacenterId;
  }

  public synchronized long nextId() {
    long currentTimeMillis = System.currentTimeMillis();
    if (currentTimeMillis < lastTimeMillis) {
      throw new RuntimeException(
          String.format("可能出现服务器时钟回拨问题，请检查服务器时间。当前服务器时间戳：%d，上一次使用时间戳：%d", currentTimeMillis,
              lastTimeMillis));
    }

    if (currentTimeMillis == lastTimeMillis) {
      sequence = (sequence + 1) & SEQUENCE_MASK;
      if (sequence == 0) {
        currentTimeMillis = tilNextMillis(lastTimeMillis);
      }
    } else {
      sequence = 0;
    }

    lastTimeMillis = currentTimeMillis;
    return ((currentTimeMillis - INIT_EPOCH) << TIMESTAMP_SHIFT) | (datacenterId
        << DATA_CENTER_ID_SHIFT) | (workerId << WORK_ID_SHIFT) | sequence;
  }

  private long tilNextMillis(long lastTimeMillis) {
    long currentTimeMillis = System.currentTimeMillis();
    while (currentTimeMillis <= lastTimeMillis) {
      currentTimeMillis = System.currentTimeMillis();
    }
    return currentTimeMillis;
  }
}
